package XML;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import java.io.IOException;

public class AddXMLDataDemo {



    //static

    public static void add(String h, String i, String j) {
        File file = new File("D:\\GitHOME\\information\\text.xml");
        DocumentBuilder newDocumentBuilder = null;
        try {
            newDocumentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        }

        Document doc = null;
        try {
            doc = newDocumentBuilder.parse(file);
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        Element root = doc.getDocumentElement();



        //创建一个新的spot节点

        Element spot = doc.createElement("spot");

        //创建spot的几个子节点

        Element name = doc.createElement("name");

        Element id = doc.createElement("id");

        Element intro = doc.createElement("intro");

     //   Element adj = doc.createElement("adj");

        //给子节点设置值
    /*    System.out.println("请输入名称：");
        Scanner na = new Scanner(System.in);
        String a=na.next();*/
        name.setTextContent(h);
    /*    System.out.println("请输入编号：");
        Scanner i = new Scanner(System.in);
        String b=i.next();*/
        id.setTextContent(i);
     /*   System.out.println("请输入简介：");
        Scanner in = new Scanner(System.in);
        String c=in.next();*/
        intro.setTextContent(j);
     /*   System.out.println("请输入路径信息：");
        Scanner ad = new Scanner(System.in);
        String d=ad.next();*/

        //将子节点追加到spot

        spot.appendChild(name);

        spot.appendChild(id);

        spot.appendChild(intro);

     //   spot.appendChild(adj);

        root.appendChild(spot);

        Transformer transformer = null;
        try {
            transformer = TransformerFactory.newInstance().newTransformer();
        } catch (TransformerConfigurationException e) {
            e.printStackTrace();
        }

        Source source = new DOMSource(doc);

        Result result = new StreamResult(file);

        try {
            transformer.transform(source, result);
        } catch (TransformerException e) {
            e.printStackTrace();
        }

    }



}

